package com.hcb.fragment;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Locale;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import com.hcb.adapter.AdapterListSearchResponder;
import com.hcb.app911.MainActivity;
import com.hcb.app911.R;
import com.hcb.constants.Constants;
import com.hcb.dto.ContactsDTO;
import com.hcb.dto.ResponderDTO;
import com.hcb.location.DistanceLocation;
import com.hcb.webservice.ServiceHandler;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.AnimationDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class ListSearchResponceFragment extends Fragment implements
		OnClickListener, OnItemClickListener {
	ListView lvSearchResponce;
	AdapterListSearchResponder adapter;
	ArrayList<Object> arrData;
	TextView txttypesearch, txtnamesearch;
	ImageView imgheadersearch;
	DistanceLocation distanceLocation;
	Dialog dialog;
	AnimationDrawable frameAnimation;
	Button btnMore;
	String typesearch = "";
	String keyword = "";
	boolean flag = false;
	Context context = null;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(
				R.layout.fragment_list_search_reponder, container, false);
		((MainActivity)this.getActivity()).getImgDetail().setImageResource(R.drawable.mydetail);
		((MainActivity)this.getActivity()).getImgHome().setImageResource(R.drawable.icon);
		btnMore = (Button) rootView.findViewById(R.id.btnMore);
		btnMore.setOnClickListener(this);
		lvSearchResponce = (ListView) rootView
				.findViewById(R.id.lvSearchResponce);

		View headersearch = inflater.inflate(R.layout.header_search_reponder,
				null, false);
		lvSearchResponce.addHeaderView(headersearch);

		txttypesearch = (TextView) headersearch
				.findViewById(R.id.txttypesearch);
		txtnamesearch = (TextView) headersearch
				.findViewById(R.id.txtnamesearch);
		imgheadersearch = (ImageView) headersearch
				.findViewById(R.id.imgheadersearch);

		distanceLocation = new DistanceLocation(getActivity());
		arrData = new ArrayList<Object>();
		adapter = new AdapterListSearchResponder(getActivity(),
				R.layout.fragment_list_search_reponder, arrData);
		lvSearchResponce.setAdapter(adapter);
		lvSearchResponce.setOnItemClickListener(this);

		Bundle bundle = getArguments();
		typesearch = bundle.getString("responder_type");

		keyword = bundle.getString("keyseach");

		if (!typesearch.equalsIgnoreCase("")) {
			if (typesearch.contains("1")) {
				txttypesearch.setText("Hospitals");
				txtnamesearch
						.setText("listings of Hospitals in orther of distance to your current location");
				imgheadersearch.setImageResource(R.drawable.hospital);
			} else if (typesearch.contains("2")) {
				txttypesearch.setText("Police Stations");
				txtnamesearch
						.setText("listings of Police Stations in orther of distance to your current location");
				imgheadersearch.setImageResource(R.drawable.police);
			} else if (typesearch.contains("3")) {
				txttypesearch.setText("Fire Services");
				txtnamesearch
						.setText("listings of Fire Services in orther of distance to your current location");
				imgheadersearch.setImageResource(R.drawable.fireservice);
			} else if (typesearch.contains("4")) {
				txttypesearch.setText("Ambulance");
				txtnamesearch
						.setText("listings of Ambulance in orther of distance to your current location");
				imgheadersearch.setImageResource(R.drawable.ambulance);
			}
			new VerySlowTask(typesearch, keyword).execute();
		}

		return rootView;
	}

	Comparator<Object> objComparator = new Comparator<Object>() {
		public int compare(Object o1, Object o2) {
			ResponderDTO dto = (ResponderDTO) o1;
			String str1 = dto.getAdded_on();
			String numberOnly1 = str1.replaceAll("[^0-9]", "");
			ResponderDTO dto2 = (ResponderDTO) o2;
			String str2 = dto2.getAdded_on();
			String numberOnly2 = str2.replaceAll("[^0-9]", "");
			int no1 = Integer.parseInt(numberOnly1);
			int no2 = Integer.parseInt(numberOnly2);
			return no1 < no2 ? -1 : no1 == no2 ? 0 : 1;
		}
	};

	@Override
	public void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

	}

	public class VerySlowTask extends AsyncTask<Void, Void, Void> {
		String _typesearch = "";
		String _keywork = "";

		public VerySlowTask(String typesearch, String keyword) {
			this._typesearch = typesearch;
			this._keywork = keyword;
			dialog = new Dialog(getActivity(), R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.GET_RESPONDER_LIST));
			nameValuePairs.add(new BasicNameValuePair("responder_type",
					_typesearch));
			nameValuePairs.add(new BasicNameValuePair("keyword", _keywork));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));

			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject json = new JSONObject(jsonStr);
					String conn = json.getString("result");
					if (conn.contains("success")) {
						JSONArray databody = json.getJSONArray("data_body");
						int n = Math.min(3, databody.length());
						if (flag) {
							int m = arrData.size();
							// int lengarr = databody.length() - m;
							for (int i = m; i < databody.length(); i++) {
								JSONObject item = databody.getJSONObject(i);
								String responder_type = item
										.getString("responder_type");
								// if (_typesearch.contains(responder_type)) {
								ResponderDTO res = new ResponderDTO();

								res.setResponder_name(item
										.getString("responder_name"));
								res.setStreet(item.getString("street"));
								res.setTown(item.getString("town"));
								res.setState(item.getString("state"));
								res.setContact_number_one(item
										.getString("contact_number_one"));
								res.setAdded_on(String.valueOf((int) distanceLocation.getDistance(
										Double.parseDouble(item
												.getString("latitude")),
										Double.parseDouble(item
												.getString("longitude"))))
										+ " miles");

								arrData.add(res);
								// }
							}
						} else {
							for (int i = 0; i < n; i++) {
								JSONObject item = databody.getJSONObject(i);
								String responder_type = item
										.getString("responder_type");
								// if (_typesearch.contains(responder_type)) {
								ResponderDTO res = new ResponderDTO();

								res.setResponder_name(item
										.getString("responder_name"));
								res.setStreet(item.getString("street"));
								res.setTown(item.getString("town"));
								res.setState(item.getString("state"));
								res.setContact_number_one(item
										.getString("contact_number_one"));
								res.setAdded_on(String.valueOf((int) distanceLocation.getDistance(
										Double.parseDouble(item
												.getString("latitude")),
										Double.parseDouble(item
												.getString("longitude"))))
										+ " miles");

								arrData.add(res);
								// }

							}
						}

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Collections.sort(arrData, objComparator);
			adapter.notifyDataSetChanged();
			dialog.dismiss();
			btnMore.setBackgroundResource(R.drawable.more);
		}

	}
	

	public class VerySlowTaskKeySearch extends AsyncTask<Void, Void, Void> {
		String _keysearch = "";

		public VerySlowTaskKeySearch(String keysearch) {
			this._keysearch = keysearch;
			dialog = new Dialog(getActivity(), R.style.NewDialog);
			dialog.setContentView(R.layout.loading);

			dialog.setCancelable(false);
			dialog.findViewById(R.id.loading_icon).setBackgroundResource(
					R.drawable.spin_animation);
			frameAnimation = (AnimationDrawable) dialog.findViewById(
					R.id.loading_icon).getBackground();
			dialog.show();
			frameAnimation.start();
		}

		@Override
		protected Void doInBackground(Void... params) {

			ServiceHandler sh = new ServiceHandler();
			List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
			nameValuePairs.add(new BasicNameValuePair("query",
					Constants.GET_RESPONDER_KEYWORD));
			nameValuePairs.add(new BasicNameValuePair("api_secret_key",
					Constants.API_KEY));
			nameValuePairs.add(new BasicNameValuePair("keyword", _keysearch));

			String jsonStr = sh.makeServiceCall(Constants.URL_SERVICE,
					ServiceHandler.POST, nameValuePairs);
			if (jsonStr != null) {
				try {
					JSONObject json = new JSONObject(jsonStr);
					String conn = json.getString("result");
					if (conn.contains("success")) {
						JSONArray databody = json.getJSONArray("data_body");
						for (int i = 0; i < databody.length(); i++) {
							JSONObject item = databody.getJSONObject(i);
							String responder_type = item
									.getString("responder_type");
							// if (_typesearch.contains(responder_type)) {
							ResponderDTO res = new ResponderDTO();

							res.setResponder_name(item
									.getString("responder_name"));
							res.setStreet(item.getString("street"));
							res.setTown(item.getString("town"));
							res.setState(item.getString("state"));
							res.setContact_number_one(item
									.getString("contact_number_one"));
							res.setAdded_on(String.valueOf((int) distanceLocation
									.getDistance(Double.parseDouble(item
											.getString("latitude")), Double
											.parseDouble(item
													.getString("longitude"))))
									+ " miles");

							arrData.add(res);
							// }

						}

					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
			} else {
				// Log.e("ServiceHandler",
				// "Couldn't get any data from the url");
			}
			return null;
		}

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			super.onPostExecute(result);
			Collections.sort(arrData, objComparator);
			adapter.notifyDataSetChanged();
			dialog.dismiss();

		}

	}

	@Override
	public void onClick(View v) {
		btnMore.setBackgroundResource(R.drawable.moref);
		flag = true;
		new VerySlowTask(typesearch, keyword).execute();

	}

	@Override
	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		if (adapter.getArrObject().size() >= 1) {
			ResponderDTO re = null;

			try {
				re = (ResponderDTO) lvSearchResponce
						.getItemAtPosition(position);
				String numberphone = re.getContact_number_one();
				// set the data
				if (!numberphone.equalsIgnoreCase("")) {
					String uri = "tel:" + numberphone.toString();
					Intent callIntent = new Intent(Intent.ACTION_CALL,
							Uri.parse(uri));

					startActivity(callIntent);
				}
			} catch (Exception e) {

				e.printStackTrace();
			}

		}

	}
}
